import { Component, OnInit} from '@angular/core';
import { Router, ActivatedRoute} from "@angular/router";
import { UserLoginService} from './user/user-login/user-login.service';
import { UserService} from './user/user.service';
import { User, RegisterInfo} from "./user/model/user-model";
import { Response} from "@angular/http";
import {GlobalService} from "./global.service";
import { Location} from '@angular/common';
import {rootRoute} from "@angular/router/src/router_module";


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent{

  url:string = this.location.path();


  constructor(
    private userLoginService:UserLoginService,
    private userService:UserService,
    private globalService:GlobalService,
    private router:Router,
    private location:Location,
  ) { }

  title = 'Acm';
  public currentUser:User;
  public registerInfo:RegisterInfo = new RegisterInfo();
  public user:User = new User();
  public examLoginInfo:ExamLoginInfo = new ExamLoginInfo();
  public test:any;
  public liFlag:any;
  public liTitle:any;


  ngOnInit(){
    console.log("ngOnInit");
    this.currentUser = this.globalService.getCurrentUser();
    console.log("currentUser:");
    console.log(this.currentUser);
    if (this.currentUser!=null&&this.currentUser.role=='admin'){
      this.liTitle = '公共题目集';
    }else {
      this.liTitle = '题目集';
    }


    this.router.onSameUrlNavigation = 'reload';

    let url = this.url;
    let start = this.url.lastIndexOf('problem-sets/') + 13;
    let end = this.url.lastIndexOf('/problems');
    this.liFlag = url.slice(start,end);
    console.log("liFlag:",this.liFlag);

    /**
     * 禁用click事件
     * @type {HTMLElement|any}
     */
    var elem = document.getElementById("li");
    elem.addEventListener("click",function(event){
      event.preventDefault(); // 阻止默认事件
      event.stopPropagation(); // 阻止冒泡
    },false);


  }

  clicked:boolean = false;
  clickLi(){
    this.clicked = true;
  }

  public doLogin():void{
    if (this.user.code==null||this.user.code==''){
      alert("请输入正确的账号");
      return;
    }else if (this.user.password==null||this.user.password==''){
      alert("请输入正确的密码");
      return;
    }
    console.log(this.user);
    this.userLoginService.login(this.user)
      .subscribe((res:Response)=>{
        console.log("登录返回的结果是:");
        let response = res.json();
        console.log(response);
        if (response.success){
          console.log("登录成功!");
          let user = new User();
          user.code = response.value.code;
          user.name = response.value.name;
          user.email = response.value.email;
          user.studentNumber = response.value.studentNumber;
          user.problemSetCodes = response.value.problemSetCodes;
          if (!response.value.roles[0]){
            user.role = 'student';
          }else {
            user.role = response.value.roles[0].code;
          }
          localStorage.setItem("currentUser",JSON.stringify(user));
          this.currentUser = user;
          //表明当前存在用户
          this.globalService.loginInfo = true;
          console.log("跳转成功!");
            //登录成功关闭登录dialog
            this.showLoginFlag = false;
          //alert("登录成功");
          if(this.location.path().indexOf("problem-sets2")>0){
            this.router.navigateByUrl('/problem-sets');
          }else{
            this.router.navigateByUrl('/problem-sets2');
          }
        }else{
          alert("登录失败!请检查账号和密码的正确性");
        }
      });
  }

  toggleFlag:boolean = true;
  showToggle:boolean = true;//子菜单展开状态
  toggleLi(){
    this.showToggle = !this.showToggle;
    let url = this.location.path();
    //如果没有进入问题界面和展开栏处于关闭状态
    if(url.indexOf("/problems")<0&&!this.showToggle){
      this.toggleFlag = false;
    }else {
      this.toggleFlag = true;
    }
    console.log("切换标题",this.showToggle);
  }

  hideToggle(){
    let url = this.location.path();
    if(url.indexOf("/problems")<0){
      this.toggleFlag = false;
    }
    if (!this.showToggle){
      this.toggleFlag = false;
    }
  }

  public doLogout(): void {
    // this.userLoginService.logout();
    localStorage.removeItem("currentUser");
    this.ngOnInit();
    console.log("message:",this.router.onSameUrlNavigation);
    //重新加载路由
    //window.location.reload();
    if(this.location.path().indexOf("home")>0){
      this.router.navigateByUrl('/home2');
    }else{
      this.router.navigateByUrl('/home');
    }
    this.currentUser = null;

   /* this.router.navigate(['/problem-sets']);
    this.router.onSameUrlNavigation = 'reload';*/
  }
  public doRegister(){
    console.log("doRegister:");
    //验证注册信息的合理性
    //1.邮箱
    let emailTest = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    if (!emailTest.test(this.registerInfo.email)){
      alert("邮箱格式错误");
      return;
    }
    //2.密码
    let pwTest = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$/;
    if (!pwTest.test(this.registerInfo.password)){
      alert("密码格式错误");
      return;
    }
    //3.重复密码
    if (this.registerInfo.password!=this.registerInfo.confirmPassword){
      alert("两次密码输入不一致");
      return;
    }
    //4.昵称验证
    if (this.registerInfo.name==null&&this.registerInfo.name==''){
      alert("请输入昵称");
      return;
    }
    let data = {code:this.registerInfo.email,password:this.registerInfo.password,name:this.registerInfo.name};
    this.userService.registerInfo(data)
      .subscribe((res:Response)=>{
        let response = res.json();
        if (response.success){
          console.log("注册成功!");
          this.showRegisterFlag = false;
          let user = new User();
          user.code = response.value.code;
          user.name = response.value.name;
          user.email = response.value.email;
          user.studentNumber = response.value.studentNumber;
          user.problemSetCodes = response.value.problemSetCodes;
          if (!response.value.roles[0]){
            user.role = 'student';
          }else {
            user.role = response.value.roles[0].code;
          }
          localStorage.setItem("currentUser",JSON.stringify(user));
          this.currentUser = user;
          //表明当前存在用户
          this.globalService.loginInfo = true;
          if(this.location.path().indexOf("problem-sets2")>0){
            this.router.navigateByUrl('/problem-sets');
          }else{
            this.router.navigateByUrl('/problem-sets2');
          }
          console.log("跳转成功!");
        }else{
          alert("注册失败！邮箱已被注册")
        }
      });
  }
  //考试登录
  public doExamLogin(){
    let data = this.examLoginInfo;
    if (data.studentNumber==null||data.studentNumber==''){
      alert("请输入正确的学号");
      return;
    }else if (data.name==null||data.name==''){
      alert("请输入正确的姓名");
      return;
    }
    data.code = 'zua-' + data.studentNumber;
    this.userService.examLogin(data)
      .subscribe((res:Response)=>{
        let data = res.json();
        if (data.success){
          console.log(data.value);
          if (data.value!=null){
            console.log("考试登录成功!");
            let user = new User();
            user.code = data.value.code;
            user.name = data.value.name;
            user.email = data.value.email;
            user.exam = true;
            user.studentNumber = data.value.studentNumber;
            user.problemSetCodes = data.value.problemSetCodes;
            if (!data.value.roles[0]){
              user.role = 'student';
            }else {
              user.role = data.value.roles[0].code;
            }
            localStorage.setItem("currentUser",JSON.stringify(user));
            this.currentUser = user;
            //登录成功关闭登录dialog
            this.hiddenDialog();
            //表明当前存在用户
            this.globalService.loginInfo = true;
            if(this.location.path().indexOf("problem-sets2")>0){
              this.router.navigateByUrl('/problem-sets');
            }else{
              this.router.navigateByUrl('/problem-sets2');
            }
            console.log("跳转成功!");
            /*//登录成功关闭登录dialog
            this.showLoginFlag = false;
            //重新加载路由
            //window.location.reload();
            this.router.navigate(['/problem-sets']);*/
          }else {
            console.log("考试登录失败!");
          }
        }else{
          alert(data.msg);
        }
      });
  }
  //忘记密码发送邮件
  forgetEmail:string;
  public sendEmail(){
    console.log("忘记密码发送邮件");
    console.log(this.forgetEmail);
    let user = new User();
    user.email = this.forgetEmail;
    this.userService.forgetPw(user)
      .subscribe((res:Response)=>{
        let data = res.json();
        if (data.success){
          console.log("发送邮件成功!");
        }
      });
  }

  showLoginFlag:boolean = false;
  showLoginDialog(){
    this.hiddenDialog();

    this.showLoginFlag = true;
  }
  showRegisterFlag:boolean = false;
  showRegisterDialog(){
    //隐藏login界面
    this.hiddenDialog();

    this.showRegisterFlag = true;
  }
  showForgetPasswordFlag:boolean = false;
  showForgetPasswordDialog(){
    this.hiddenDialog();

    this.showForgetPasswordFlag = true;
  }
  showExamLoginFlag:boolean = false;
  showExamLoginDialog(){
    this.hiddenDialog();

    this.showExamLoginFlag = true;
  }

  hiddenDialog(){
    this.showLoginFlag = false;
    this.showRegisterFlag = false;
    this.showForgetPasswordFlag = false;
    this.showExamLoginFlag = false;
  }

  problemList(){
    let url = this.location.path();
    let setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/"));
    if(url.indexOf("/problems")>0){
      setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/problems"));
    }
    console.log("setCode:",setCode);
    this.router.navigateByUrl("/problem-sets/"+setCode+"/problems");

    document.getElementById("problemList").classList.add("active");
    document.getElementById("submitList").classList.remove("active");
    document.getElementById("rankList").classList.remove("active");

  }

  submitList(){
    let url = this.location.path();
    let setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/"));
    if(url.indexOf("/problems")>0){
      setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/problems"));
    }
    console.log("setCode:",setCode);
    this.router.navigateByUrl("/problem-sets/"+setCode+"/submissions");

    document.getElementById("problemList").classList.remove("active");
    document.getElementById("submitList").classList.add("active");
    document.getElementById("rankList").classList.remove("active");

  }

  rankList(){
    let url = this.location.path();
    let setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/"));
    if(url.indexOf("/problems")>0){
      setCode = url.substring(url.indexOf("problem-sets")+13,url.lastIndexOf("/problems"));
    }

    console.log("setCode:",setCode);
    this.router.navigateByUrl("/problem-sets/"+setCode+"/rankings");

    document.getElementById("problemList").classList.remove("active");
    document.getElementById("submitList").classList.remove("active");
    document.getElementById("rankList").classList.add("active");
  }

}

export class ExamLoginInfo{
  code:string;
  studentNumber:string;
  name:string;
}
